﻿using Core.DataAccess.Model.iTool.Gateway;
using HandlerContextOptions;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UserCenter.Interfaces;

namespace UserCenter.Implements
{
    public class Menu : IMenu
    {

        public async Task<MenuDeleteResult> Delete(MenuDeleteRequset requset)
        {
            await using (iToolGatewayContext context = new iToolGatewayContext())
            {
                var menu = await context.SysMenus.FindAsync(requset.MenuKey);
                if (menu == null)
                {
                    return new MenuDeleteResult
                    {
                        IsSuccessful = false,
                        Description = "菜单不存在"
                    };
                }
                else
                {
                    var roleMenu = await context.SysRoleMenus.Where(item => item.RoleMenuMenuIds.Contains($",{menu.MenuId},")).FirstAsync();
                    roleMenu.RoleMenuMenuIds = roleMenu.RoleMenuMenuIds.Replace($",{menu.MenuId},", ",");
                    context.SysMenus.Remove(menu);
                    await context.SaveChangesAsync();

                    return new MenuDeleteResult
                    {
                        IsSuccessful = true
                    };
                }
            }
        }

        public async Task<GetMenuResult> Get(GetMenuRequset requset)
        {
            await using (iToolGatewayContext context = new iToolGatewayContext())
            {
                if (requset.UserKey > 0)
                {
                    var userRole = await context.SysUserRoles.Where(item => item.UserRoleUserId == requset.UserKey).FirstAsync();
                    var role = await context.SysRoles.Where(item => item.RoleId == userRole.UserRoleId).FirstAsync();
                    var roleMenu = await context.SysRoleMenus.Where(item => item.RoleMenuRoleId == userRole.UserRoleId).FirstOrDefaultAsync();

                    if (role.RoleName == "超级管理员" || role.RoleId == 1)
                    {
                        return new GetMenuResult
                        {
                            Menus = await context.SysMenus.ToListAsync(),
                            IsSuccessful = true
                        };
                    }
                    else if (string.IsNullOrWhiteSpace(roleMenu.RoleMenuMenuIds))
                    {
                        return new GetMenuResult
                        {
                            Menus = new List<SysMenu>(),
                            IsSuccessful = true
                        };
                    }
                    else
                    {
                        var menuIds = roleMenu.RoleMenuMenuIds.TrimStart(',').TrimEnd(',').Split(',');
                        var menuidx = menuIds.Where(item => !string.IsNullOrWhiteSpace(item)).Select(item => int.Parse(item)).ToList();

                        return new GetMenuResult
                        {
                            Menus = await context.SysMenus.Where(item => menuidx.Contains(item.MenuId)).ToListAsync(),
                            IsSuccessful = true
                        };
                    }
                }
                else
                {
                    return new GetMenuResult
                    {
                        Menus = await context.SysMenus.ToListAsync(),
                        IsSuccessful = true
                    };
                }
            }
        }

        public async Task<MenuInsertResult> Insert(MenuInsertRequset requset)
        {
            await using (iToolGatewayContext context = new iToolGatewayContext())
            {
                await context.SysMenus.AddAsync(requset);
                await context.SaveChangesAsync();

                if (requset.RoleKey > 0)
                {
                    var roleMenu = await context.SysRoleMenus.Where(item => item.RoleMenuRoleId == requset.RoleKey).FirstAsync();

                    if (string.IsNullOrWhiteSpace(roleMenu.RoleMenuMenuIds))
                    {
                        roleMenu.RoleMenuMenuIds = $",{requset.MenuId},";
                    }
                    else
                    {
                        roleMenu.RoleMenuMenuIds += $"{requset.MenuId},";
                    }

                    await context.SaveChangesAsync();
                }

                return new MenuInsertResult { IsSuccessful = true };
            }
        }
        public async Task<MenuModifyResult> Modify(MenuModifyRequset requset)
        {
            await using (iToolGatewayContext context = new iToolGatewayContext())
            {
                var menu = await context.SysMenus.FindAsync(requset.MenuId);
                if (menu == null)
                {
                    return new MenuModifyResult
                    {
                        IsSuccessful = false,
                        Description = "菜单不存在"
                    };
                }
                else
                {
                    context.SysMenus.Update(menu);

                    if (requset.RoleKey > 0)
                    {
                        var roleMenuOld = await context.SysRoleMenus.Where(item => item.RoleMenuMenuIds.Contains($",{menu.MenuId},")).FirstAsync();
                        roleMenuOld.RoleMenuMenuIds = roleMenuOld.RoleMenuMenuIds.Replace($",{menu.MenuId},", ",");


                        var roleMenu = await context.SysRoleMenus.Where(item => item.RoleMenuRoleId == requset.RoleKey).FirstAsync();
                        if (string.IsNullOrWhiteSpace(roleMenu.RoleMenuMenuIds))
                            roleMenu.RoleMenuMenuIds = $",{requset.MenuId},";
                        else
                            roleMenu.RoleMenuMenuIds += $"{requset.MenuId},";
                    }

                    await context.SaveChangesAsync();

                    return new MenuModifyResult
                    {
                        IsSuccessful = true
                    };
                }
            }
        }
        public async Task<List<MenuListOpetions>> GetMenuList()
        {
            await using (iToolGatewayContext context = new iToolGatewayContext())
            {
                List<MenuListOpetions> options = new List<MenuListOpetions>();
                var result = await context
                     .SysMenus.ToListAsync();
                var a = optionlist(result, false);

                return a;
            }
        }
        public List<MenuListOpetions> optionlist(List<SysMenu> menu, bool me)
        {
            List<MenuListOpetions> options = new List<MenuListOpetions>();
            foreach (var item in menu)
            {
                List<MenuListOpetions> option = new List<MenuListOpetions>();
                if (item.MenuParentId == null)
                {

                    var child = menu.Where(a => a.MenuParentId == item.MenuId).ToList();
                    if (child.Count > 0)
                    {
                        option = optionlist(child, true);
                    }
                    options.Add(new MenuListOpetions()
                    {
                        MenuID = item.MenuId,
                        MenuName = item.MenuName,
                        MenuParentID = item.MenuParentId,
                        MenuOptions = option,

                    });
                    me = false;
                }
                if (me)
                {
                    options.Add(new MenuListOpetions()
                    {
                        MenuID = item.MenuId,
                        MenuName = item.MenuName,
                        MenuParentID = item.MenuParentId,
                        MenuOptions = option,

                    });

                }

            }
            return options;

        }
    }
}
